<template>
        <div class="payment">
            <van-nav-bar
                    title="订单支付"
                    left-arrow
                    :fixed="true"
                    class="my-nav"
                    @click-left="$router.back(-1)"
            />
            <div style="margin-top: 50px;">
                <div class="van-notice-bar" style="text-align: center">
                    <div style="margin: auto;"> 剩余付款时间: <span class="red">59分59秒</span></div>
                </div>
                <van-panel v-for="order in orders" :key="order.order_number">
                    <van-nav-bar slot="header" style="color: #666">
                        <div slot="left">
                            <van-icon name="shop" style="color:red;margin-right: 6px"/>
                            {{order.shopName}}
                        </div>
                        <div slot="right" v-text="order.order_number">
                            4654654
                        </div>
                    </van-nav-bar>
                    <van-cell title="实付金额"><span class="red">{{order.total_price | yuan}}</span></van-cell>
                </van-panel>
                <van-cell-group>
                    <van-cell title="总支付金额"><span class="red">{{totalMoney | yuan}}</span></van-cell>
                    <van-field
                            v-model="userRemarks"
                            label="备注说明"
                            type="textarea"
                            placeholder="请录入你要说明的信息"
                            rows="1"
                            autosize
                    />
                </van-cell-group>
                <div class="pay_way_group">
                    <div>
                        <img v-if="img" :src="img" alt="" style="width: 50%" @c>
                    </div>
                    <van-uploader :after-read="onRead" accept="image/gif, image/jpeg" multiple :max-size="1024*1024">
                        <div style="border: 1px dashed #eee; padding: 10px;">
                            <van-icon style="font-size: 30px" name="photograph" />
                            <br>
                            <span style="font-size: 14px;">上传支付截图</span>
                        </div>
                    </van-uploader>
                </div>
                <van-button class="pay_submit" @click="paySubmit" :loading="isSubmit" type="primary"  bottomAction style="z-index: 100">去支付</van-button>
            </div>


    </div>
</template>

<script>

  import {
    Toast,ImagePreview
  } from 'vant';
  import bus from  '../../bus'
  import {orderDetail} from '../../api/order'
  import {upload ,save} from '../../api/pay'
  export default {
    name: "payment",
    data() {
      return {
        isSubmit: false,
        orderCodes: bus.state.orderCodes,
        orders: [],
        file: undefined,
        userRemarks: '',
        img:undefined,
      }
    },
    methods: {
      paySubmit() {
        this.isSubmit = true;
        if(this.file){
          upload(this.file, imgUrl=>{
            let payInfoArray = this.orderCodes.map(code=>createPayInfo(code,imgUrl,this.userRemarks))
            save(payInfoArray, _=> {
              this.isSubmit=false;
              bus.state.orderCodes=[];
              Toast('支付成功')
            })
          })
        }else{
          Toast('请上传支付截图')
        }

      },
      onRead(file) {
        ImgToBase64(file.file, 720,  (base64)=> {
          this.img = base64;//预览页面上预留一个img元素，载入base64
          this.file = file.file
        });
      },
      loadOrder(){
        this.orders = [];
        this.orderCodes.forEach(code=>orderDetail({code},data=>{
           this.orders.push(data);
        }))
      }
    },
    filters: {
      yuan (price){
        return '¥' + Number.parseInt(price).toFixed(2);
      }
    },
    computed: {
      totalMoney(){
        return this.orders.reduce((x,item)=>x+item.total_price, 0);
      }
    },
    mounted (){
      if(this.orderCodes.length<1){
        this.$router.push('/home')
      }
      this.loadOrder();
    }
  }

  function createPayInfo(orderCode, imgUrl, userRemarks) {
    return {
      orderCode,
      type:0,
      url: imgUrl,
      userRemarks
    }
  }

  // 图片压缩
  function ImgToBase64(file, maxLen, callBack) {
    let img = new Image();

    let reader = new FileReader();//读取客户端上的文件
    reader.onload = function () {
      let url = reader.result;//读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的.所以必须使用reader.onload，
      img.src = url;//reader读取的文件内容是base64,利用这个url就能实现上传前预览图片
    };
    img.onload = function () {
      //生成比例
      let width = img.width, height = img.height;
      //计算缩放比例
      let rate = 1;
      if (width >= height) {
        if (width > maxLen) {
          rate = maxLen / width;
        }
      } else {
        if (height > maxLen) {
          rate = maxLen / height;
        }
      };
      img.width = width * rate;
      img.height = height * rate;
      //生成canvas
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      let base64 = canvas.toDataURL('image/jpeg', 0.9);
      callBack(base64);
    };
    reader.readAsDataURL(file);
  }
</script>

<style lang="less" scoped>
    .pay_way_group {
        margin: 20px auto;
        text-align: center;
        color: #666;
    }
    .time_down {
        background-color: #fffeec;
        padding: 10px 15px;
    }

    .pay_submit {
        position: fixed;
        bottom: 0;
        width: 100%;
    }

    .pay_way_group img {
        vertical-align: middle;
    }

    .pay_way_title {
        padding: 15px;
        background-color: #fff;
    }
    .red{
        color: red;
    }
</style>
